<template>
  <el-main>
    <h1 style="margin-bottom: 20px">{{ this.id ? '编辑物品' : '新建物品'}}</h1>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="物品名称">
            <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="物品图片">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="getAuthHeaders()"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
</template>
<script>
  export default {
    props: {
      id: {type: String}
    },
    data() {
      return {
        form: {
          name: '',
          icon: '',
        },
      }
    },
    created() {
      this.id && this.fetch()
    },
    methods: {
      handleAvatarSuccess(res) {
        this.$set(this.form, 'icon', res.url)
      },
      async onSubmit() {
        let res
        if(this.id) {
          res = await this.$http.put(`curd/item/${this.id}`, this.form)
        } else {
          res = await this.$http.post('curd/item', this.form)
        }
        if(res.data.code === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
          this.$router.push('/item/list')
        }
      },
      async fetch() {
        const res = await this.$http.get(`curd/item/${this.id}`)
        this.form = res.data
      },
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>